package com.longrise.android.byjk.plugins.course.coursedetail.courseadapter;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.CourseTrainDirBean;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CourseCache;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ToDispatchStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.utils.PrintLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by godliness on 2017/7/25.
 * <p>
 * 课程详情适配器，兼容目录
 */

public final class CourseDetailAdapter extends BaseExpandableListAdapter {

    private static final String TAG = "CourseDetailAdapter";

    /**
     * 课程详情数据结构
     */
    private List<CourseTrainDirBean.Dirinfo> mDirinfos;
    private final StringBuilder mStrBuilder = new StringBuilder();

    private boolean mBlue;

    private final HashMap<Integer, Integer> mChildCountMap = new HashMap<>(32);

    private final int mChildTop = 0;
    private final int mChildBottom = 1;

    private String mCourseId;
    private String mStudentNo;
    private int mGroupType;

    /**
     * 定位课件
     */
    private String mCwid = "";

    /**
     * 兼容【目录】item点击样式
     */
    private int mItemSelector = R.drawable.by_item_selecter_bg;

    /**
     * 兼容【目录】是否是在下载详情
     */
    private boolean mFromCache;

    /**
     * 一级菜单View
     */
    private class GroupItems {
        private TextView mText_Title;
        private TextView mText_BL;
        private ImageView mImage_Row;
        private TextView mTvState;
        private View mViewLine;
    }

    /**
     * 二级菜单View
     */
    private class ChildItems {
        private ImageView mImageView;
        private TextView mText_SubTitle;
        private TextView mText_TopLine;
        private TextView mText_BottomLine;
        private TextView mTvState;
        private TextView mTvHasqa;
    }

    private OnChildItemClickListener mClickListener;

    public CourseDetailAdapter() {
        init();
    }

    private void init() {
        //缓存详情页，【目录】已学完/总数量，选修/必修，通过/未通过  状态
        if (CourseCache.Flag.FLAG_FROM_COURSE_DOWNLOADED.equals(CourseCache.getCacheFlag())) {
            mFromCache = true;
        } else {
            mFromCache = false;
        }
    }

    /**
     * item回调
     */
    public void onItemClick(CourseTrainDirBean.Nextnodeinfo nextnodeinfo, String courseId, String studentNo, int... position) {
    }

    /**
     * @param videoParams 封装成videoParams
     */
    public void onItemClick(VideoParams videoParams) {

    }

    /**
     * @param attachToDirinfos 是否将模拟测试题添加到列表尾部 课程详情需要，但是播放器页面展示不需要
     * @param isNotifyData     是否直接通知刷新
     */
    public void setData(CourseTrainDirBean bean, boolean attachToDirinfos, boolean isNotifyData) {
        if (bean == null) {
            return;
        }
        CourseTrainDirBean.Result result = bean.result;
        if (result == null) {
            return;
        }
        mCourseId = result.courseid;
        mStudentNo = result.studentno;
        mGroupType = result.grouptype;
        CourseTrainDirBean.Traindirstruct traindirstruct = result.traindirstruct;
        if (traindirstruct == null) {
            return;
        }
        mDirinfos = traindirstruct.dirinfo;
        mBlue = result.issinguptrain && result.isablestudy;

        //兼容 模拟测试题
        if (attachToDirinfos) {
            addExercisesSubject(bean);
        }

        if (isNotifyData) {
            notifyData();
        }
    }

    public void notifyData() {
        this.notifyDataSetChanged();
    }

    /**
     * 兼容 目录
     */
    public void setItemSelector(int itemSelector) {
        this.mItemSelector = itemSelector;
    }

    /**
     * 兼容 模拟测试题  将模拟测试题数据结构添加到列表尾部
     */
    private void addExercisesSubject(CourseTrainDirBean bean) {
        try {
            attachExercisesToList(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析模拟测试题到列表
     */
    private void attachExercisesToList(CourseTrainDirBean bean) {
        CourseTrainDirBean.Result result = bean.result;
        List<CourseTrainDirBean.Exconfigbean> exconfigbeans = result.exconfigbean;
        if (exconfigbeans == null) {
            return;
        }
        int size = exconfigbeans.size();
        if (size <= 0) {
            return;
        }
        CourseTrainDirBean.Dirinfo dirinfo = bean.new Dirinfo();
        dirinfo.nextnodeinfo = new ArrayList<>();
        int finishCount = 0;
        for (CourseTrainDirBean.Exconfigbean exconfigbean : exconfigbeans) {
            if (exconfigbean.istest == 1) {
                finishCount++;
            }
            CourseTrainDirBean.Nextnodeinfo nextnodeinfo = bean.new Nextnodeinfo();
            nextnodeinfo.cwid = exconfigbean.id;  //课件id
            nextnodeinfo.name = exconfigbean.testtitle;  //课件name
            nextnodeinfo.istest = exconfigbean.istest;  //课件学习状态
            nextnodeinfo.isfinish = exconfigbean.istest == 1 ? true : false;
            nextnodeinfo.recordid = exconfigbean.recordid;  //学习记录id
            nextnodeinfo.cwstyle = ToDispatchStudy.TEST;
            dirinfo.nextnodeinfo.add(nextnodeinfo);
        }
        dirinfo.name = "模拟测试题";
        dirinfo.finishedcwcount = finishCount;
        dirinfo.ismusttrain = result.isexmusttrain;
        dirinfo.cwcount = size;
        mDirinfos.add(dirinfo);
        PrintLog.e(TAG, "isexmusttrain: " + result.isexmusttrain);
    }

    @Override
    public int getGroupCount() {
        return mDirinfos == null ? 0 : mDirinfos.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (mDirinfos == null) {
            return 0;
        }
        CourseTrainDirBean.Dirinfo dirinfo = mDirinfos.get(groupPosition);
        if (dirinfo == null) {
            return 0;
        }
        return dirinfo.nextnodeinfo == null ? 0 : dirinfo.nextnodeinfo.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        if (mDirinfos == null) {
            return null;
        }
        CourseTrainDirBean.Dirinfo dirinfo = mDirinfos.get(groupPosition);
        if (dirinfo == null) {
            return null;
        }
        if (dirinfo.nextnodeinfo != null) {
            mChildCountMap.put(groupPosition, dirinfo.nextnodeinfo.size());
        }
        return dirinfo;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        if (mDirinfos == null) {
            return null;
        }
        CourseTrainDirBean.Dirinfo dirinfo = mDirinfos.get(groupPosition);
        if (dirinfo == null) {
            return null;
        }
        return dirinfo.nextnodeinfo == null ? null : dirinfo.nextnodeinfo.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupItems items;
        this.onGroupExpanded(groupPosition);
        if (convertView == null) {
            items = new GroupItems();
            convertView = View.inflate(parent.getContext(), R.layout.expandparentitem, null);
            convertView.setBackground(parent.getContext().getResources().getDrawable(mItemSelector));
            items.mText_Title = (TextView) convertView.findViewById(R.id.text_parent_title);
            items.mText_BL = (TextView) convertView.findViewById(R.id.text_parent_bl);
            items.mImage_Row = (ImageView) convertView.findViewById(R.id.image_row);
            items.mTvState = (TextView) convertView.findViewById(R.id.tv_group_state);
            items.mViewLine = convertView.findViewById(R.id.view_parentline);
            convertView.setTag(items);
        } else {
            items = (GroupItems) convertView.getTag();
        }
        CourseTrainDirBean.Dirinfo dirinfo = (CourseTrainDirBean.Dirinfo) getGroup(groupPosition);
        if (dirinfo == null) {
            return convertView;
        }
        items.mText_Title.setText(dirinfo.name);
        //兼容 目录
        items.mText_Title.setTextColor((mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#333333") : Color.parseColor("#FFFFFF")));

        items.mText_BL.setVisibility(View.VISIBLE);

        //兼容目录
        if (!mFromCache) {
            mStrBuilder.setLength(0);
            mStrBuilder.append("（").append(dirinfo.finishedcwcount).append("/").append(dirinfo.cwcount).append("）");
            items.mText_BL.setText(mStrBuilder.toString());
        }

        //兼容目录
        items.mText_BL.setTextColor(mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#333333") : Color.parseColor("#FFFFFF"));
        items.mImage_Row.setImageResource(isExpanded ? R.drawable.icon_up : R.drawable.icon_down);
        items.mTvState.setText(mFromCache ? "" : dirinfo.ismusttrain ? "【必修】" : "【选修】");

        //兼容目录
        items.mTvState.setTextColor(dirinfo.ismusttrain ? Color.parseColor("#FF0000") : mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#999999") : Color.parseColor("#FFFFFF"));
        items.mViewLine.setVisibility(isExpanded ? View.GONE : View.VISIBLE);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildItems items;
        if (convertView == null) {
            items = new ChildItems();
            convertView = View.inflate(parent.getContext(), R.layout.childitems, null);
            convertView.setBackground(parent.getContext().getResources().getDrawable(mItemSelector));
            items.mImageView = (ImageView) convertView.findViewById(R.id.image_childt_title);
            items.mText_SubTitle = (TextView) convertView.findViewById(R.id.text_child_bl);
            items.mText_TopLine = (TextView) convertView.findViewById(R.id.text_topline);
            items.mText_BottomLine = (TextView) convertView.findViewById(R.id.text_bottomline);
            items.mTvState = (TextView) convertView.findViewById(R.id.image_buffer);
            items.mTvHasqa = (TextView) convertView.findViewById(R.id.tv_hasqa);
            convertView.setTag(items);
        } else {
            items = (ChildItems) convertView.getTag();
        }
        CourseTrainDirBean.Nextnodeinfo nextnodeinfo = (CourseTrainDirBean.Nextnodeinfo) getChild(groupPosition, childPosition);
        if (nextnodeinfo != null) {
            items.mText_SubTitle.setText(nextnodeinfo.name);
            //兼容目录
            if (!mFromCache) {
                items.mTvState.setText(nextnodeinfo.isfinish ? convertView.getContext().getString(R.string.course_ispass) : convertView.getContext().getString(R.string.course_unispass));
            }
            items.mText_SubTitle.setTextColor(nextnodeinfo.isfinish ? Color.parseColor("#009966") : Color.parseColor("#999999"));
            items.mTvHasqa.setVisibility(nextnodeinfo.hasqa ? View.VISIBLE : View.GONE);

            //兼容 目录
            items.mTvState.setTextColor(nextnodeinfo.isfinish ? Color.parseColor("#009966") : mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#999999") : Color.parseColor("#FFFFFF"));
            //当前播放课件
            boolean atomic = mCwid.equals(nextnodeinfo.cwid);
            if (mFromCache) {
                items.mText_SubTitle.setTextColor((atomic ? Color.parseColor("#E50012") : mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#999999") : Color.parseColor("#FFFFFF")));
            } else {
                items.mText_SubTitle.setTextColor(atomic ? Color.parseColor("#E50012") : nextnodeinfo.isfinish ? Color.parseColor("#009966") : mItemSelector == R.drawable.by_item_selecter_bg ? Color.parseColor("#999999") : Color.parseColor("#FFFFFF"));
            }
            items.mImageView.setImageResource(atomic ? R.drawable.red_arrow : mBlue ? R.drawable.curr_stop : R.drawable.start_grew);
        }
        items.mText_TopLine.setVisibility(childPosition == mChildTop ? View.INVISIBLE : View.VISIBLE);
        Integer childInteger = mChildCountMap.get(groupPosition);
        int childLength = childInteger == null ? 0 : childInteger;
        items.mText_BottomLine.setVisibility(childPosition == childLength - mChildBottom ? View.INVISIBLE : View.VISIBLE);
        setItemClick(convertView, nextnodeinfo, groupPosition, childPosition);
        return convertView;
    }

    private void setItemClick(final View view, final CourseTrainDirBean.Nextnodeinfo nextnodeinfo, final int... position) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        if (nextnodeinfo != null) {
                            VideoParams videoParams = AssistAdapter.assistGenerateVideoParams(nextnodeinfo, position);
                            addParamsToOnItemClick(videoParams);
                        }
                    }
                });
            }
        });
    }

    private void addParamsToOnItemClick(VideoParams videoParams) {
        if (videoParams == null) {
            return;
        }
        videoParams.mCourseId = mCourseId;
        videoParams.mStudentNo = mStudentNo;
        videoParams.mGroupType = mGroupType;
        PrintLog.e(TAG, "videoParams: " + videoParams);
        if (mClickListener != null) {
            mClickListener.onItemClick(videoParams);
        }
    }

    /**
     * @param cwid 根据cwid找到在adapter中的位置
     */
    public int[] getCwidInAdapterIndex(String cwid) {
        if (mDirinfos == null || TextUtils.isEmpty(cwid)) {
            return null;
        }
        this.mCwid = cwid;
        return AssistAdapter.assistGetCwidInAdapterIndex(mDirinfos, cwid);
    }

    /**
     * 更新课件在适配器中状态
     */
    public boolean updateCwidStateInAdapter(int[] position) {
        if (mDirinfos == null || position == null) {
            return false;
        }
        boolean adapterIsUpdated = false;
        try {
            adapterIsUpdated = AssistAdapter.assistUpdateCwidState(mDirinfos, position);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintLog.e(TAG, "updateInAdapter: " + adapterIsUpdated);
        return adapterIsUpdated;
    }

    /**
     * 找到第一个未通过的课件，如果全部通过默认为第一个
     */
    public void startNoFinishCwid() {
        if (mDirinfos == null) {
            return;
        }
        VideoParams videoParams = AssistAdapter.assistStartNoFinishCwid(mDirinfos);
        addParamsToOnItemClick(videoParams);
    }

    public interface OnChildItemClickListener {
        void onItemClick(VideoParams params);

    }

    public void setItemClickListener(OnChildItemClickListener clickListener) {
        this.mClickListener = clickListener;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}
